#include <iostream>
#include <string>
#include <unistd.h>
#include <mysql/mysql.h>

const std::string host = "127.0.0.1";
const std::string user = "my";
const std::string passwd = "Mysql907245";
const std::string db = "test_debug";
const unsigned int port = 3306;

int main()
{
    // std::cout << "mysql client version: " << mysql_get_client_info() << std::endl;

    MYSQL *my = mysql_init(nullptr);
    if (my == nullptr)
    {
        std::cerr << "init MySQL error" << std::endl;
        return 1;
    }
    if (mysql_real_connect(my, host.c_str(), user.c_str(), passwd.c_str(), db.c_str(), port, nullptr, 0) == nullptr)
    {
        std::cerr << "connect MySQL error" << std::endl;
        return 2;
    }
    // std::cout << "connect success" << std::endl;
    // sleep(10);

    // std::string sql;
    // while (true)
    // {
    //     std::cout << "MySQL>>> ";
    //     if (!getline(std::cin, sql) || sql == "quit")
    //     {
    //         std::cout << "bye" << std::endl;
    //         break;
    //     }

    //     int n = mysql_query(my, sql.c_str());
    //     if (n == 0)
    //     {
    //         std::cout << sql << "success:" << n << std::endl;
    //     }
    //     else
    //     {
    //         std::cerr << sql << "failed:" << n << std::endl;
    //     }
    // }

    // std::string sql = "insert user values (1,'tom', '32', '123456789')";
    // std::string sql = "insert user values (2,'peter', '26', '17324689')";
    // update和delete同理

    mysql_set_character_set(my, "utf8");
    std::string sql = "select * from user";

    int n = mysql_query(my, sql.c_str());
    if (n == 0)
        std::cout << sql << " success" << std::endl;
    else
    {
        std::cerr << sql << " failed" << std::endl;
        return 3;
    }
    // 这里存储了查找出来的表的信息
    MYSQL_RES *result = mysql_store_result(my);
    if (nullptr == result)
    {
        std::cerr << "mysql_store_result error" << std::endl;
        return 4;
    }
    // select之后就和my没有关系了，全都是和结果集有关系的
    int rows = mysql_num_rows(result);
    int fields = mysql_num_fields(result);

    std::cout << "行: " << rows << std::endl;
    std::cout << "列: " << fields << std::endl;

    MYSQL_FIELD *fields_array = mysql_fetch_fields(result);
    for(int i = 0; i < fields; ++i)
    {
        std::cout << fields_array[i].name << "\t";
    }
    std::cout << std::endl;


    // 内容
    for (int i = 0; i < rows; ++i)
    {
        MYSQL_ROW row = mysql_fetch_row(result);
        for (int j = 0; j < fields; ++j)
        {
            std::cout << row[j] << "\t";
        }
        std::cout << std::endl;
    }
    mysql_free_result(result);
    mysql_close(my);
    return 0;
}